<template>
  <div class="admin-information-container">
    <el-card class="information-card">
      <template #header>
        <div class="card-header">
          <span>管理员信息</span>
          <el-button
              type="primary"
              @click="editMode = !editMode"
              style="background-color: #409EFF; border-color: #409EFF;"
          >
            <el-icon><Edit /></el-icon>
            {{ editMode ? '取消编辑' : '编辑信息' }}
          </el-button>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载中...
      </div>

      <div v-else class="information-section">
        <el-form
            ref="formRef"
            :model="adminForm"
            label-width="100px"
            :rules="rules"
            v-if="editMode"
        >
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="头像">
                <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleAvatarChange"
                >
                  <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="adminForm.username" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="realName">
                <el-input v-model="adminForm.realName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="adminForm.gender">
                  <el-radio :value="1">男</el-radio>
                  <el-radio :value="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthDate">
                <el-date-picker
                    v-model="adminForm.birthDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="adminForm.phone" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="adminForm.email" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="adminForm.idCard" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input v-model="adminForm.address" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <el-button @click="cancelEdit">取消</el-button>
                <el-button
                    type="primary"
                    @click="saveAdminInfo"
                    style="background-color: #409EFF; border-color: #409EFF;"
                >
                  保存
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-descriptions :column="1" border v-else>
          <el-descriptions-item label="用户名">{{ adminInfo.username || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ adminInfo.realName || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="头像">
            <el-avatar :size="60" :src="adminInfo.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
          </el-descriptions-item>
          <el-descriptions-item label="性别">{{ formatGender(adminInfo.gender) }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ formatDate(adminInfo.birthDate) }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ adminInfo.phone || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ adminInfo.email || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ adminInfo.idCard || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ adminInfo.address || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="用户类型">{{ formatUserType(adminInfo.userType) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="adminInfo.status === 1 ? 'success' : 'danger'">
              {{ adminInfo.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ formatDateTime(adminInfo.registerTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Loading, Edit, Plus } from '@element-plus/icons-vue'

// const BASE_URL = 'http://localhost:8080'

const adminInfo = ref({})
const adminForm = ref({})
const loading = ref(false)
const editMode = ref(false)
const formRef = ref(null)
const avatarFile = ref(null)
const avatarPreview = ref('')

// 表单验证规则
const rules = {
  phone: [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  email: [
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ],
  idCard: [
    {pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号', trigger: 'blur'}
  ]
}

// 处理头像变化
const handleAvatarChange = (file) => {
  const isImage = file.raw.type.includes('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }

  avatarFile.value = file.raw
  avatarPreview.value = URL.createObjectURL(file.raw)
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) return null

  try {
    const formData = new FormData()
    formData.append('file', avatarFile.value)

    const token = localStorage.getItem('adminToken')
    const headers = {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'multipart/form-data'
    }

    const response = await axios.post(`${BASE_URL}/api/v1/upload`, formData, { headers })
    if (response.data.code === 2000) {
      return response.data.data
    }
    throw new Error(response.data.msg || '上传失败')
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传头像失败: ' + error.message)
    return null
  }
}

// 加载管理员信息
const loadAdminInfo = async () => {
  try {
    loading.value = true

    const userString = localStorage.getItem('user')
    const userData = JSON.parse(userString);
    if (!userString) {
      throw new Error('未找到用户信息，请重新登录')
    }

    //const user = JSON.parse(userString)
    const userId = userData.user.userId
    console.log('Current userId from localStorage:', userId)

    const token = localStorage.getItem('token')
    // const token = localStorage.getItem('adminToken')
    if (!token) {
      throw new Error('未找到管理员Token，请重新登录')
    }

    const headers = { Authorization: `Bearer ${token}` }

    const response = await axios.get(`${BASE_URL}/api/v1/admins/detail`, {
      params: { userId },
      headers
    })

    console.log('API response:', response.data)

    if (response.data.code === 2000) {
      adminInfo.value = response.data.data
      adminForm.value = JSON.parse(JSON.stringify(response.data.data))
      avatarPreview.value = response.data.data.avatarUrl || ''
    } else {
      throw new Error(response.data.msg || '获取管理员信息失败')
    }
  } catch (error) {
    console.error('加载管理员信息失败:', error)
    ElMessage.error(error.message || '加载管理员信息失败')

    if (error.response?.status === 401) {
      localStorage.removeItem('adminId')
      localStorage.removeItem('adminToken')
      window.location.href = '/login'
    }
  } finally {
    loading.value = false
  }
}

// 保存管理员信息
const saveAdminInfo = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      loading.value = true
      const token = localStorage.getItem('adminToken')
      if (!token) {
        throw new Error('未找到管理员Token，请重新登录')
      }

      const headers = { Authorization: `Bearer ${token}` }

      // 上传头像
      const avatarUrl = await uploadAvatar()
      if (avatarUrl) {
        adminForm.value.avatarUrl = avatarUrl
      }

      // 确保传递当前管理员的userId
      const updateData = {
        ...adminForm.value,
        userId: adminInfo.value.userId
      }

      const response = await axios.post(
          `${BASE_URL}/api/v1/admins/update`,
          updateData,
          { headers }
      )

      if (response.data.code === 2000) {
        ElMessage.success('信息更新成功')
        loadAdminInfo() // 重新加载数据
        editMode.value = false
        avatarFile.value = null
      } else {
        throw new Error(response.data.msg || '更新失败')
      }
    } catch (error) {
      console.error('更新管理员信息失败:', error)
      ElMessage.error(error.message || '更新管理员信息失败')
    } finally {
      loading.value = false
    }
  })
}

// 取消编辑
const cancelEdit = () => {
  editMode.value = false
  adminForm.value = JSON.parse(JSON.stringify(adminInfo.value))
  avatarPreview.value = adminInfo.value.avatarUrl || ''
  avatarFile.value = null
}

const formatGender = (gender) => {
  return gender === 1 ? '男' : gender === 2 ? '女' : '未知'
}

const formatDate = (dateString) => {
  return dateString ? new Date(dateString).toLocaleDateString() : '未设置'
}

const formatDateTime = (dateString) => {
  return dateString ? new Date(dateString).toLocaleString() : '未设置'
}

const formatUserType = (userType) => {
  const types = {
    6: '区域管理员',
    7: '普通管理员',
    8: '超级管理员'
  }
  return types[userType] || `未知类型(${userType})`
}

onMounted(() => {
  loadAdminInfo()
})
</script>

<style scoped>
.admin-information-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.information-card {
  border-radius: 4px;
  border: none;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #304156;
}

.information-section {
  padding: 20px;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-descriptions-item {
  padding: 12px 0;
}

.el-descriptions-item :deep(.el-descriptions__label) {
  width: 120px;
  color: #909399;
}

.el-descriptions-item :deep(.el-descriptions__content) {
  color: #304156;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: #606266;
}

.is-loading {
  animation: rotating 2s linear infinite;
  margin-right: 8px;
  color: #409EFF;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.el-form {
  margin-top: 20px;
}

.el-form-item :deep(.el-form-item__label) {
  color: #606266;
}

.el-radio-group {
  line-height: 32px;
}

/* 头像上传样式 */
.avatar-uploader {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style>